package com.hyh.order.listenner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyh.order.dao.OrderMapper;
import com.hyh.order.domain.Orders;
import com.hyh.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class OrderRedisListener {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OrderMapper orderMapper;



    /*
     * @description: 定时任务 删除未支付的订单
     * @param:
     * @return:
     * @author
     * @date: 2024/3/25 15:26
     */
    public  void listenerOrderExpire(Integer userId,Integer productId){
        ScheduledExecutorService schedule =
                Executors.newScheduledThreadPool(1);
        schedule.schedule(() -> {
            // 检查订单是否存在，如果存在则执行取消订单的操作
            if (Boolean.TRUE.equals(stringRedisTemplate.hasKey("order:" + userId + productId))) {
                // 获取订单信息
                LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Orders::getUserId, userId).eq(Orders::getProductId, productId).eq(Orders::getOrderStatus, 0);
                orderMapper.delete(queryWrapper);
                // 删除redis中的订单信息
                stringRedisTemplate.delete("order:" + userId + productId);
            }
        }, 10, TimeUnit.MINUTES);
    }
}
